# accounts/views.py
from django.shortcuts import render, redirect
from .models import User,Clothing,Face,Pose
from django.contrib.auth.decorators import login_required
import os
import subprocess
import json
from django.http import JsonResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import get_object_or_404
from django.contrib.auth import authenticate, login as auth_login, logout



def register(request):
    if request.method == 'POST':
        face_image_path = request.POST.get('face_image_path')  # 获取上传的图片地址
        clothing_image_path = request.POST.get('clothing_image_path')
        pose_image_path = request.POST.get('pose_image_path')
        
        username = request.POST['username']
        password = request.POST['password']
        name=request.POST['name']
        height = float(request.POST['height'])
        weight = float(request.POST['weight'])
        age = int(request.POST['age'])
        gender=request.POST['gender']
        user = User(username=username, password=password,name=name, height=height, weight=weight, age=age,gender=gender)
        user.save()
        
        new_clothing = Clothing(user=user, image_path=clothing_image_path)  # 创建新的衣服记录
        new_clothing.save()  # 保存到数据库


        new_face = Face(user=user, image_path=face_image_path)  # 创建新的面容记录
        new_face.save()  # 保存到数据库

        new_pose=Pose(user=user,image_path=pose_image_path)
        new_pose.save()
        

        return redirect('login')  # 注册成功后跳转到登录页面
    return render(request, 'register.html')


def login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        
        if username == 'admin' and password == '000':
            return redirect('admin_page')  # Redirect to admin page if admin logs in
        
        try:
            user = User.objects.get(username=username)
            if user.password == password:
                return redirect('platform', user_id=user.id)  # 登录成功，跳转到平台页面
            else:
                return render(request, 'login.html', {'error': 'Invalid password'})
        except User.DoesNotExist:
            return render(request, 'login.html', {'error': 'User does not exist'})
    return render(request, 'login.html')

def admin_page(request):
    users = User.objects.all()
    if request.method == 'POST':
        user_id = request.POST.get('user_id')
        user_to_delete = get_object_or_404(User, id=user_id)
        user_to_delete.delete()
        return redirect('admin_page')  # tRefresh the page after deleion

    return render(request, 'admin.html', {'users': users})


def platform(request, user_id):
    user = User.objects.get(id=user_id)  # 获取当前用户信息
    
    # 如果是 POST 请求，表示用户在上传新衣服或面容图片
    if request.method == 'POST':
        if 'height' in request.POST and 'weight' in request.POST and 'age' in request.POST:
            # Update user information
            user.height = float(request.POST['height'])
            user.weight = float(request.POST['weight'])
            user.age = int(request.POST['age'])
            user.save()  # Save changes to the database
        else:
            image_path = request.POST.get('image_path')  # 获取上传的图片地址
            
            if 'clothing' in request.POST:
                # 上传衣服图片
                new_clothing = Clothing(user=user, image_path=image_path)  # 创建新的衣服记录
                new_clothing.save()  # 保存到数据库
            elif 'face' in request.POST:
                # 上传面容图片
                new_face = Face(user=user, image_path=image_path)  # 创建新的面容记录
                new_face.save()  # 保存到数据库
            elif 'pose' in request.POST:
                new_pose = Pose(user=user, image_path=image_path)
                new_pose.save()
        
        return redirect('platform', user_id=user.id)  # 保存后刷新页面
    
    return render(request, 'platform.html', {'user': user})



def ai_view(request):
    # 获取所有图片地址
    faces = Face.objects.all()
    poses = Pose.objects.all()
    clothings = Clothing.objects.all()
    print('hi')
    if request.method == 'POST' :
        # 接收前端传递的选中图片 ID
        print("收到请求：", request.POST)
        face_id = request.POST.get('face_id')
        pose_id = request.POST.get('pose_id')
        clothing_id = request.POST.get('clothing_id')
        try:
            # 获取选中图片的相对路径
            face = Face.objects.get(id=face_id)
            pose = Pose.objects.get(id=pose_id)
            clothing = Clothing.objects.get(id=clothing_id)

            # 将相对路径转换为绝对路径
            base_path = "/root/autodl-tmp/smart_dressing/accounts/static/"
            face_path = os.path.join(base_path, face.image_path.strip('/'))
            pose_path = os.path.join(base_path, pose.image_path.strip('/'))
            clothing_path = os.path.join(base_path, clothing.image_path.strip('/'))

            # AI 模型输出路径
            output_path = os.path.join(base_path, "images/output.jpg")

            # 调用 AI 模型
            script_path = "/root/autodl-tmp/IMAGDressing/inference_IMAGdressing_ipa_controlnetpose.py"
            print("Face path:" ,face_path)
            subprocess.run([
                "python", script_path,
                "--cloth_path", clothing_path,
                "--face_path", face_path,
                "--pose_path", pose_path
            ], check=True)

            # 返回生成图片的相对路径
            return JsonResponse({
                "success": True,
                "output_path": "/images/output.jpg"
            })

        except Exception as e:
            return JsonResponse({
                "success": False,
                "error": str(e)
            })

    return render(request, 'Ai.html', {
        'faces': faces,
        'poses': poses,
        'clothings': clothings
    })




def sk_view(request):
    generated_image_path = None  # 用于存储生成的图片路径

    if request.method == 'POST':
        if 'generate' in request.POST:
            # 获取用户输入的图片地址
            img_in = request.POST.get('image_path')  # 用户输入的相对路径，例如 'static/images/model.jpg'

            # 转换为绝对路径
            base_path = "/root/autodl-tmp/smart_dressing/accounts/static/images/"
            img_in_absolute = os.path.join(base_path, os.path.basename(img_in))

            # 定义生成的图片路径（相对路径为 static/images/model_SK.jpg）
            img_out_relative = "images/" + os.path.splitext(os.path.basename(img_in))[0] + "_SK.jpg"  # static/images/model_SK.jpg
            img_out_absolute = os.path.join(base_path, os.path.basename(img_out_relative))

            # 调用外部程序
            script_path = "/root/autodl-tmp/smart_dressing/accounts/algorithm/SKpoint.py"
            try:
                subprocess.run(
                    ['python', script_path, '--img_in', img_in_absolute],
                    check=True
                )
            except subprocess.CalledProcessError as e:
                return JsonResponse({'success': False, 'error': f"程序运行失败: {e}"}, status=500)

            # 返回生成的图片相对路径
            generated_image_path = img_out_relative  # 例如 'images/model_SK.jpg'

        elif 'save' in request.POST:
            # 保存生成的图片路径到数据库
            generated_image_path = request.POST.get('generated_image_path')
            if generated_image_path:
                # 假设我们已经有用户登录的逻辑（user 从请求中获取当前用户）
                user = User.objects.get(id=1)  # 示例，获取第一个用户
                Pose.objects.create(user=user, image_path=generated_image_path)
                return redirect('platform', user_id=user.id)  # 保存成功后跳转到 platform.html

    return render(request, 'SK.html', {
        'generated_image_path': generated_image_path
    })

def logout_view(request):
    logout(request)
    return redirect('login')  # Redirect to the login page after logging out

def delete_clothing(request, clothing_id):
    clothing = get_object_or_404(Clothing, id=clothing_id)
    clothing.delete()
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))  # Redirect back to the previous page

def delete_face(request, face_id):
    face = get_object_or_404(Face, id=face_id)
    face.delete()
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))  # Redirect back to the previous page

def delete_pose(request, pose_id):
    pose = get_object_or_404(Pose, id=pose_id)
    pose.delete()
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))  # Redirect back to the previous page


